import asyncio
from config import ENTITY, API_ID, API_HASH, PHONE, BOT_NAME, DEFAULT_SPEAKER_NAME

# https://docs.telethon.dev/en/latest/
# https://pypi.org/project/telegram-cloud/

from telethon import TelegramClient
from telethon.tl.types import DocumentAttributeAudio
import mimetypes
import os
from mutagen.mp3 import MP3

# TODO add Exceptions hendling and typing
def send_audio(filename, artist="", title=""):
    client = TelegramClient(ENTITY, int(API_ID), API_HASH)
    client.start(phone=PHONE)
    mimetypes.add_type('audio/aac', '.aac')
    mimetypes.add_type('audio/ogg', '.ogg')
    mp3_file_info = MP3(filename).info

    duration = mp3_file_info.length

    if artist == "":
        artist = DEFAULT_SPEAKER_NAME

    if title == "":
        title = filename

    
    cover_path = f"covers/{artist}.jpg"
    if os.path.isfile(cover_path):
        album_cover_path = cover_path
    else:
        album_cover_path = "covers/cover.jpg"

    async def send_file():
        await client.send_file(
                BOT_NAME,
                filename,
                caption=str(artist + '=' + title + '=' + str(duration)),
                use_cache=False,
                part_size_kb=512,
                thumb=album_cover_path,
                attributes=[DocumentAttributeAudio(
                        int(duration),
                        title=title,
                        performer=artist)]
                )

    loop = asyncio.get_event_loop()
    loop.run_until_complete(send_file())

